package com.lw.spring.utils;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;

import java.lang.reflect.Method;

/**
 * @author Administrator
 * @version 1.0
 * @description:
 * @date 2022/3/5 16:42
 */
public class CgLibFactory {
    public static <T> T getService(Class<T> tClass) throws Exception{
        T newInstance = tClass.newInstance();
        Enhancer enh=new Enhancer();
        enh.setSuperclass(tClass);
        enh.setCallback(new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {

                TransactionUtil.start();
                Object invoke = method.invoke(newInstance, objects);
                TransactionUtil.commit();
                LogUtils.addLog();
                return invoke;
            }
        });
        Object o = enh.create();
        return (T) o;
    }
}
